package com.cloudkinto.service.amazon.inbound.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.AsinShipmentDo;
import com.cloudkinto.entity.AsinShipmentItemDo;
import com.cloudkinto.entity.ShopDo;
import com.cloudkinto.service.amazon.AmazonBaseServiceImpl;
import com.cloudkinto.service.amazon.inbound.AsinShipmentItemService;
import com.cloudkinto.service.amazon.inbound.AsinShipmentService;
import com.cloudkinto.service.amazon.inbound.vo.AsinShipmentTransportContentEntity;
import com.cloudkinto.service.amazon.inbound.vo.ShipmentEntity;
import com.cloudkinto.service.amazon.inbound.vo.ShipmentItemEntity;
import com.cloudkinto.service.amazon.vo.AmazonMarketDto;
import com.cloudkinto.utils.amazon.AmazonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.parseObject;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hua
 * @since 2021-09-07
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class AsinShipmentServiceImpl extends AmazonBaseServiceImpl<AsinShipmentDao, AsinShipmentDo> implements AsinShipmentService {
    @Autowired
    private AsinShipmentDao dao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private AsinShipmentDao asinShipmentDao;
    @Autowired
    private AsinShipmentItemDao asinShipmentItemDao;
    @Autowired
    private AsinShipmentItemService asinShipmentItemService;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private CountryCodeDao countryCodeDao;


    @Override
    public SingleResult addInit() {
//        Map paramMap = new HashMap();
//        String body = null;
//        try {
//            body = AmazonUtil.spAPidoGet(GlobalConstants.AmazonSPURL + "/fba/inbound/v0/shipments/" + "FBA15CQJ3HWF" + "/transport", getAccessToken(), getAwsSTSSessionToken(), paramMap);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        JSONObject payload = JSONObject.parseObject(body).getJSONObject("payload").getJSONObject("TransportContent").getJSONObject("TransportHeader");
//        String shipmentType = payload.getString("ShipmentType");
//        String IsPartnered = payload.getString("IsPartnered");
//
//        System.out.println(payload);
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        AsinShipmentDo entityDo = new AsinShipmentDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(AsinShipmentDo entityDo, Long userId) {
        entityDo.setCreateTime(new Date());
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(AsinShipmentDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*AsinShipmentDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(AsinShipmentDo entityDo, Long userId) {
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(AsinShipmentDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        AsinShipmentDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }


    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(AsinShipmentDo entityDo, Long userId) {

    }

    // @Override
    // public AsinShipmentDetailRes detail(Long id) {
    //     AsinShipmentDo entityDo = dao.selectById(id);
    //     AsinShipmentDetailRes res = new AsinShipmentDetailRes();
    //     BeanUtils.copyProperties(entityDo, res);
    //     res.setTransportMsg(entityDo.getShipmentType());
    //     return handlerDetailAfter(res);
    // }
    //
    // //查询明细之后要执行的业务定制处理
    // private AsinShipmentDetailRes handlerDetailAfter(AsinShipmentDetailRes res) {
    //     DicBusinessItemDo shipmentStatusDo = dicBusinessItemDao.selectById(res.getShipmentStatus());
    //     if (shipmentStatusDo != null) {
    //         res.setShipmentStatusName(shipmentStatusDo.getDicItemValue());
    //     }
    //
    //     Map<String, String> map = new HashMap<>();
    //     map.put("shipmentId", res.getShipmentId());
    //     List<AsinShipmentItemRes> list = asinShipmentItemService.getList(map);
    //     res.setAsinShipmentItemResList(list);
    //     int totalProductQuantity = list.stream().mapToInt(AsinShipmentItemRes::getShippedQuantity).sum();
    //     //货件内商品
    //     res.setContent(list.size() + "种SKU " + totalProductQuantity + "件商品");
    //     return res;
    // }
    //
    // @Override
    // public SingleResult pageInit(Long userId) {
    //     Map result = new HashMap();
    //     //店铺及站点
    //
    //     // result.put("tress", shopService.getAuthorizedShopMarketMapList(userId));
    //
    //
    //     List<Map> shipStatusList = new ArrayList<>();
    //     List<DicBusinessItemDo> itemDoList = dicBusinessItemDao.selectList(new LambdaQueryWrapper<DicBusinessItemDo>().eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.shipmentStatus));
    //     itemDoList.forEach(item -> {
    //         Map itemMap = new HashMap();
    //         itemMap.put("id", item.getId());
    //         itemMap.put("value", item.getDicItemValue());
    //         shipStatusList.add(itemMap);
    //     });
    //     result.put("shipStatusList", shipStatusList);
    //     return SingleResult.success(result);
    // }
    //
    // @Override
    public SingleResult createPlanInit(Long userId) {
        Map result = new HashMap();
        //     //店铺及站点
        //     result.put("tress", shopService.getAuthorizedShopMarketMapList(userId));
        //     //标签类型
        //     List<Map> labelTypeList = new ArrayList<>();
        //     String[] arr = {"SELLER_LABEL", "AMAZON_LABEL_ONLY", "AMAZON_LABEL_PREFERRED"};
        //     for (int i = 0; i < 3; i++) {
        //         Map labelItemMap = new HashMap();
        //         int id = i + 1;
        //         labelItemMap.put("id",String.valueOf(id));
        //         labelItemMap.put("value", arr[i]);
        //         labelTypeList.add(labelItemMap);
        //     }
        //
        //     result.put("labelTypeList", labelTypeList);
        //     //发货地址
        //     List<Map> countryCodeList = new ArrayList<>();
        //     List<CountryCodeDo> itemDoList = countryCodeDao.selectList(new QueryWrapper<CountryCodeDo>().gt("id", 0));
        //     itemDoList.forEach(item -> {
        //         Map itemMap = new HashMap();
        //         itemMap.put("id", item.getId());
        //         itemMap.put("value", item.getIso31661());
        //         countryCodeList.add(itemMap);
        //     });
        //     result.put("countryCodeList", countryCodeList);
        return SingleResult.success(result);
    }
    //
    // @Override
    // public List<AsinShipmentRes> getList(Map<String, String> map) {
    //     QueryWrapper<AsinShipmentDo> wrapper = queryBuild(map);
    //     List<AsinShipmentDo> list = this.list(wrapper);
    //     List<AsinShipmentRes> result = handlerListAfter(list);
    //     return result;
    // }
    //
    // @Override
    // public PageResult getListPage(Map<String, String> map) {
    //     QueryWrapper<AsinShipmentDo> wrapper = queryBuild(map);
    //     IPage<AsinShipmentDo> page = pageInit(map);
    //     page = this.page(page, wrapper);
    //     List<AsinShipmentRes> resList = handlerListAfter(page.getRecords());
    //     PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
    //     return result;
    // }
    //
    // //查询分页列表之后对列表数据的处理
    // private List<AsinShipmentRes> handlerListAfter(List<AsinShipmentDo> list) {
    //     List<AsinShipmentRes> result = new ArrayList<>();
    //     list.forEach(et -> {
    //         AsinShipmentRes res = new AsinShipmentRes();
    //         BeanUtils.copyProperties(et, res);
    //         ShopDo shopDo = shopDao.selectById(et.getShopId());
    //         if (shopDo != null) {
    //             res.setShopName(shopDo.getShopName());
    //         }
    //         DicBusinessItemDo statusItemDo = dicBusinessItemDao.selectById(et.getShipmentStatus());
    //         if (statusItemDo != null) {
    //             res.setShipmentStatusName(statusItemDo.getDicItemValue());
    //         }
    //         result.add(res);
    //     });
    //     return result;
    // }

    private IPage<AsinShipmentDo> pageInit(Map<String, String> map) {
        IPage<AsinShipmentDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<AsinShipmentDo> queryBuild(Map<String, String> map) {
        //todo 加上companyId 判断
        QueryWrapper<AsinShipmentDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.eq("shop_id", map.get("shopId"));
        } else {
            // Map relationMap = userShopRelationService.buildUserShopRelationMap(new HashMap(), Long.parseLong(map.get("userId")));
            // if (relationMap.get("shop_ids") != null)
            //     wrapper.in("shop_id", relationMap.get("shopIds"));
            // else
            //     wrapper.eq("shop_id", null);
        }
        if (StringUtils.isNotBlank(map.get("marketPlaceId"))) {
            wrapper.eq("market_place_id", map.get("marketPlaceId"));
        }
        if (StringUtils.isNotBlank(map.get("shipmentStatus"))) {
            wrapper.eq("shipment_status", map.get("shipmentStatus"));
        }
        wrapper.orderByDesc("id");
        return wrapper;
    }


    @Override
    public void getShipments(Long shopId, Long companyId, Date begin, Date end) {
        if (shopId == null) {
            List<ShopDo> shopDoList = shopDao.selectList(new LambdaQueryWrapper<ShopDo>().eq(ShopDo::getCompanyId, companyId));
            for (ShopDo shopDo : shopDoList) {
                getShipments(shopDo.getId(), companyId, begin, end);
            }
        } else {
            ShopDo shopDo = shopDao.selectById(shopId);
            if (shopDo == null) {
                throw new BizException("请选择店铺");
            }
            if (StringUtils.isBlank(shopDo.getAmzSpLwa()))
                return;

//        List<ShopMarketPlaceDo> shopMarketPlaceDos = shopMarketPlaceDao.selectList(new LambdaQueryWrapper<ShopMarketPlaceDo>().eq(ShopMarketPlaceDo::getShopId, shopId));


            Map paramMap = new HashMap();
            paramMap.put("LastUpdatedAfter", TimeUtils.formatDate(begin, GlobalConstants.TIME_FORMAT_STR, "GMT"));
            paramMap.put("LastUpdatedBefore", TimeUtils.formatDate(end, GlobalConstants.TIME_FORMAT_STR, "GMT"));
            paramMap.put("ShipmentStatusList", "WORKING,SHIPPED,RECEIVING,CANCELLED,DELETED,CLOSED,ERROR,IN_TRANSIT,DELIVERED,CHECKED_IN");

            paramMap.put("QueryType", "DATE_RANGE");
            paramMap.put("MarketplaceId", GlobalConstants.marketplaceId);
            getShipments(paramMap, companyId, shopDo);
        }
    }

    public void getShipments(Map paramMap, Long companyId, ShopDo shopDo) {
        String body = null;
        AmazonMarketDto amazonMarketDo = new AmazonMarketDto();

        try {
            body = AmazonUtil.spAPidoGet(GlobalConstants.AmazonSPAPIURL + "/fba/inbound/v0/shipments", getAccessToken(shopDo), getAwsSTSSessionToken(3L), paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (body != null) {
            JSONObject payload = parseObject(body).getJSONObject("payload");
            if (payload == null) {
                JSONArray errors = parseObject(body).getJSONArray("errors");
                JSONObject jsonObject = errors.getJSONObject(0);
                log.debug(jsonObject.getString("message"));
                throw new BizException(jsonObject.getString("message"));
            } else {
                List<ShipmentEntity> shipmentEntities = JSONObject.parseArray(payload.get("ShipmentData").toString(), ShipmentEntity.class);
                if (shipmentEntities != null) {
                    shipmentEntities.forEach(shipmentEntity -> {
                        //shipmentItem信息
                        String itemBody = null;
                        Map itemParamMap = new HashMap();
                        itemParamMap.put("MarketplaceId", GlobalConstants.marketplaceId);
                        try {
                            itemBody = AmazonUtil.spAPidoGet(GlobalConstants.AmazonSPAPIURL + "/fba/inbound/v0/shipments/" + shipmentEntity.getShipmentId() + "/items", getAccessToken(shopDo), getAwsSTSSessionToken(amazonMarketDo.getId()), itemParamMap);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        JSONObject itemPayload = parseObject(itemBody).getJSONObject("payload");
                        List<ShipmentItemEntity> shipmentItemEntities = JSONObject.parseArray(itemPayload.get("ItemData").toString(), ShipmentItemEntity.class);

                        //运输方式
                        Map shipmentTypeMap = new HashMap();
                        String shipmentTypeBody = null;
                        try {
                            shipmentTypeBody = AmazonUtil.spAPidoGet(GlobalConstants.AmazonSPAPIURL + "/fba/inbound/v0/shipments/" + shipmentEntity.getShipmentId() + "/transport", getAccessToken(shopDo), getAwsSTSSessionToken(amazonMarketDo.getId()), shipmentTypeMap);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
//                    JSONObject transportHeader = JSONObject.parseObject(shipmentTypeBody).getJSONObject("payload").getJSONObject("TransportContent").getJSONObject("TransportHeader");

                        JSONObject shipmentTypePayload = parseObject(shipmentTypeBody).getJSONObject("payload");
                        AsinShipmentTransportContentEntity shipmentTransportContentEntity = null;
                        if (shipmentTypePayload != null) {
                            shipmentTransportContentEntity = parseObject(shipmentTypeBody, AsinShipmentTransportContentEntity.class);
                        }
//                    //发货地址测试
                        Map shipmentAddressMap = new HashMap();
                        String shipmentAddressBody = null;
                        try {
                            shipmentAddressBody = AmazonUtil.spAPidoGet(GlobalConstants.AmazonSPAPIURL + "/fba/outbound/brazil/v0/shipments/" + shipmentEntity.getShipmentId(), getAccessToken(shopDo), getAwsSTSSessionToken(amazonMarketDo.getId()), shipmentAddressMap);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        JSONObject object = parseObject(shipmentAddressBody);

                        AsinShipmentDo asinShipmentDo = dao.selectOne(new LambdaQueryWrapper<AsinShipmentDo>().eq(AsinShipmentDo::getShipmentId, shipmentEntity.getShipmentId()));
                        if (asinShipmentDo == null) {
                            asinShipmentDo = new AsinShipmentDo();
                        }
                        if (shipmentTransportContentEntity != null) {

                            // String shipmentType = shipmentTransportContentEntity.getTransportContent().getTransportHeader().getShipmentType();
                            // String isPartnered = shipmentTransportContentEntity.getTransportContent().getTransportHeader().getIsPartnered();
                            // String sellerId = shipmentTransportContentEntity.getTransportContent().getTransportHeader().getSellerId();
                            //插入补货主数据
                            // asinShipmentDo.setShipmentType(shipmentType);
                            // asinShipmentDo.setIsPartnered(isPartnered);
                            // asinShipmentDo.setSellerId(sellerId);
                        }
                        asinShipmentDo.setCompanyId(companyId);
                        asinShipmentDo.setShipmentId(shipmentEntity.getShipmentId());
                        asinShipmentDo.setShopId(shopDo.getId());
                        asinShipmentDo.setMarketPlaceId(amazonMarketDo.getId());
                        asinShipmentDo.setMSkus(shipmentItemEntities.size());
                        asinShipmentDo.setShipmentStatus(getShipmentStatus(shipmentEntity.getShipmentStatus()));
                        int quantityShipped = shipmentItemEntities.stream().mapToInt(ShipmentItemEntity::getQuantityShipped).sum();
                        int quantityReceived = shipmentItemEntities.stream().mapToInt(ShipmentItemEntity::getQuantityReceived).sum();
                        asinShipmentDo.setShippedQuantity(quantityShipped);
                        asinShipmentDo.setReceivedQuantity(quantityReceived);
                        asinShipmentDo.setDestination(shipmentEntity.getDestinationFulfillmentCenterId());
                        asinShipmentDo.setShipmentName(shipmentEntity.getShipmentName());
                        // asinShipmentDo.setAddressLine(shipmentEntity.getShipFromAddress().getAddressLine1());
                        // asinShipmentDo.setAddressName(shipmentEntity.getShipFromAddress().getName());
                        // asinShipmentDo.setPostalCode(shipmentEntity.getShipFromAddress().getPostalCode());
                        // asinShipmentDo.setCountryCode(shipmentEntity.getShipFromAddress().getCountryCode());
                        Long shipStatus = asinShipmentDo.getShipmentStatus();
                        if (asinShipmentDo.getId() == null) {
                            dao.insert(asinShipmentDo);
                        } else {
                            dao.updateById(asinShipmentDo);
                        }
                        String shipmentId = asinShipmentDo.getShipmentId();
                        //先删除原先的
                        // asinShipmentItemDao.delete(new LambdaQueryWrapper<AsinShipmentItemDo>().eq(AsinShipmentItemDo::getShipmentId, shipmentId));
                        //插入item 信息
                        shipmentItemEntities.forEach(shipmentItemEntity -> {
                            AsinShipmentItemDo asinShipmentItemDo1 = asinShipmentItemDao.selectOne(new LambdaQueryWrapper<AsinShipmentItemDo>().eq(AsinShipmentItemDo::getShipmentId, shipmentId)
                                    .eq(AsinShipmentItemDo::getCommoditySku, shipmentItemEntity.getSellerSKU()).last("limit 1"));
                            AsinShipmentItemDo asinShipmentItemDo = null;
                            if (asinShipmentItemDo1 == null) {
                                asinShipmentItemDo = new AsinShipmentItemDo();
                            } else {
                                asinShipmentItemDo = asinShipmentItemDo1;
                            }
                            asinShipmentItemDo.setShipmentId(shipmentId);
                            asinShipmentItemDo.setCommoditySku(shipmentItemEntity.getSellerSKU());
                            asinShipmentItemDo.setFnsku(shipmentItemEntity.getFulfillmentNetworkSKU());
                            asinShipmentItemDo.setShippedQuantity(shipmentItemEntity.getQuantityShipped());
                            asinShipmentItemDo.setReceivedQuantity(shipmentItemEntity.getQuantityReceived());
                            int onway = DicBusinessItemConstant.shipmentStatusSHIPPED.equals(shipStatus) || DicBusinessItemConstant.shipmentStatusINTRANSIT.equals(shipStatus) || DicBusinessItemConstant.shipmentStatusDELIVERED.equals(shipStatus) || DicBusinessItemConstant.shipmentStatusCHECKEDIN.equals(shipStatus)
                                    ? shipmentItemEntity.getQuantityShipped() : 0;
                            asinShipmentItemDo.setOnWayQuantity(onway);
                            asinShipmentItemDo.setInCaseQuantity(shipmentItemEntity.getQuantityInCase());
                            if (asinShipmentItemDo.getId() == null) {
                                asinShipmentItemDao.insert(asinShipmentItemDo);
                            } else {
                                asinShipmentItemDao.updateById(asinShipmentItemDo);
                            }
                        });
                    });
                }
                String nextToken = payload.getString("NextToken");
                if (nextToken != null && !"".equals(nextToken)) {
                    paramMap.put("NextToken", nextToken);
                    paramMap.put("QueryType", "NEXT_TOKEN");
                    getShipments(paramMap, companyId, shopDo);
                }
            }
        }
    }

    public Long getShipmentStatus(String status) {
        Long dic = null;
        switch (status) {
            case "WORKING":
                dic = DicBusinessItemConstant.shipmentStatusWORKING;
                break;
            case "SHIPPED":
                dic = DicBusinessItemConstant.shipmentStatusSHIPPED;
                break;
            case "RECEIVING":
                dic = DicBusinessItemConstant.shipmentStatusRECEIVING;
                break;
            case "CANCELLED":
                dic = DicBusinessItemConstant.shipmentStatusCANCELLED;
                break;
            case "DELETED":
                dic = DicBusinessItemConstant.shipmentStatusDELETED;
                break;
            case "CLOSED":
                dic = DicBusinessItemConstant.shipmentStatusCLOSED;
                break;
            case "ERROR":
                dic = DicBusinessItemConstant.shipmentStatusERROR;
                break;
            case "IN_TRANSIT":
                dic = DicBusinessItemConstant.shipmentStatusINTRANSIT;
                break;
            case "DELIVERED":
                dic = DicBusinessItemConstant.shipmentStatusDELIVERED;
                break;
            case "CHECKED_IN":
                dic = DicBusinessItemConstant.shipmentStatusCHECKEDIN;
                break;
        }
        return dic;
    }
    //
    // @Override
    // public SingleResult createInboundShipmentPlan(Long shopId, Long marketplaceId,String LabelPrepPreference, ShipAddress address, List<InboundShipmentPlanRequestItem> list) {
    //     ShopDo shopDo = shopDao.selectById(shopId);
    //     if (shopDo == null) {
    //         throw new BizException("请选择店铺");
    //     }
    //     AmazonMarketPlaceDo amazonMarketPlaceDo = amazonMarketPlaceDao.selectById(marketplaceId);
    //     //市场
    //     AmazonMarketDo amazonMarketDo = amazonMarketDao.selectById(amazonMarketPlaceDo.getMarketId());
    //
    //     Map paramMap = new HashMap();
    //     paramMap.put("ShipFromAddress", address);
    //     paramMap.put("LabelPrepPreference", LabelPrepPreference);
    //     paramMap.put("InboundShipmentPlanRequestItems", list);
    //     String body = null;
    //     try {
    //         body = AmazonUtil.spAPidoPOST(GlobalConstants.AmazonSPAPIURL+ "/fba/inbound/v0/plans", getAccessToken(shopId), getAwsSTSSessionToken(shopDo.getMarketId()), paramMap, JSONObject.toJSONString(paramMap));
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //     JSONObject payload = JSONObject.parseObject(body).getJSONObject("payload");
    //
    //     if (body != null) {
    //         //JSONObject payload = JSONObject.parseObject(body).getJSONObject("payload");
    //         if (payload == null) {
    //             JSONArray errors = JSONObject.parseObject(body).getJSONArray("errors");
    //             JSONObject jsonObject = errors.getJSONObject(0);
    //             log.debug(jsonObject.getString("message"));
    //             //throw new BizException(jsonObject.getString("message"));
    //             return SingleResult.failure("500", jsonObject.getString("message"));
    //
    //         }else{
    //             JSONArray jsonArray = payload.getJSONArray("InboundShipmentPlans");
    //             for (int i = 0; i < jsonArray.size(); i++) {
    //                 JSONObject jb = jsonArray.getJSONObject(i);
    //                 String shipmentId = jb.getString("ShipmentId");
    //                 String centerId = jb.getString("DestinationFulfillmentCenterId");
    //                 JSONObject addressReturn = jb.getJSONObject("ShipToAddress");
    //
    //                 AsinShipmentDo asinShipmentDo = new AsinShipmentDo();
    //                 asinShipmentDo.setShipmentId(shipmentId);
    //                 asinShipmentDo.setShopId(shopId);
    //                 asinShipmentDo.setMarketPlaceId(marketplaceId);
    //                 //从亚马逊返回数据中拿到插入数据库
    //                 asinShipmentDo.setDestination(centerId);
    //                 asinShipmentDo.setShipmentName(address.getShipmentName());
    //                 asinShipmentDo.setAddressLine(address.getAddressLine1());
    //                 asinShipmentDo.setAddressName(address.getName());
    //                 asinShipmentDo.setPostalCode(address.getPostalCode());
    //                 asinShipmentDo.setCountryCode(address.getCountryCode());
    //                 asinShipmentDo.setPackageType(address.getPackageType());
    //                 asinShipmentDo.setTelephone(address.getTelephone());
    //                 asinShipmentDo.setTips(address.getTips());
    //                 //shippedQuantity和receiveQuantity为0 需要在更改
    //                 asinShipmentDo.setShippedQuantity(0);
    //                 asinShipmentDo.setShipmentStatus(278L);
    //                 asinShipmentDo.setReceivedQuantity(0);
    //
    //                 //从请求体中拿到放到数据库中
    //                 asinShipmentDo.setLabelType(LabelPrepPreference);
    //                 asinShipmentDo.setCity(address.getCity());
    //                 asinShipmentDo.setDistrictOrCounty(address.getDistrictOrCounty());
    //                 asinShipmentDo.setStateOrProvinceCode(address.getStateOrProvinceCode());
    //                 //将第一个页面输入的数据放到jsonarray中，等确认申报时再保存
    //                 //dao.insert(asinShipmentDo);
    //                 jb.put("asinShipmentDo", asinShipmentDo);
    //
    //                 for (int j = 0; j < list.size(); j++) {
    //                     AsinShipmentItemDo asinShipmentItemDo = new AsinShipmentItemDo();
    //                     asinShipmentItemDo.setShipmentId(shipmentId);
    //                     asinShipmentItemDo.setCommoditySku(list.get(j).getSellerSKU());
    //                     asinShipmentItemDo.setShippedQuantity(list.get(j).getQuantity());
    //                     //创建入库的申报数量，创建后不得更改
    //                     asinShipmentItemDo.setDeclareQuantity(list.get(j).getQuantity());
    //                     //将第一个页面输入的数据放到jsonarray中，等确认申报时再保存
    //                     //asinShipmentItemDao.insert(asinShipmentItemDo);
    //                 }
    //                 jb.put("asinShipmentItemDoList", list);
    //             }
    //         }
    //     }
    //     JSONArray jsonArray = payload.getJSONArray("InboundShipmentPlans");
    //
    //     for (int i = 0; i < jsonArray.size(); i++) {
    //         JSONObject jb = jsonArray.getJSONObject(i);
    //         //获取返回数据中list【items】
    //         JSONArray jsArray = jb.getJSONArray("Items");
    //         int totalNum = 0;
    //         List<String> skuList = new ArrayList<>();
    //         for (int j = 0; j < jsArray.size(); j++) {
    //             JSONObject jsObject = jsArray.getJSONObject(j);
    //             totalNum += (Integer.valueOf(jsObject.getString("Quantity")));
    //             skuList.add(jsObject.getString("FulfillmentNetworkSKU"));
    //         }
    //         List<String> skuList2 = skuList.stream().distinct().collect(Collectors.toList());
    //         int mskuNum = skuList2.size();
    //         jb.put("mskuNum", mskuNum);
    //         jb.put("totalNum", totalNum);
    //         //将发货地址通过jsonArray传到创建货物运输接口中 作为调用亚马逊接口的参数
    //         jb.put("shipFromAddress", address);
    //     }
    //     return SingleResult.success(jsonArray);
    // }
    //
    // public void createInboundShipment(Long shopId, Long marketPlaceId,JSONArray jsonArray,String shipmentName) {
    //     ShopDo shopDo = shopDao.selectById(shopId);
    //     if (shopDo == null) {
    //         throw new BizException("请选择店铺");
    //     }
    //     AmazonMarketPlaceDo amazonMarketPlaceDo = amazonMarketPlaceDao.selectById(marketPlaceId);
    //     //市场
    //     AmazonMarketDo amazonMarketDo = amazonMarketDao.selectById(amazonMarketPlaceDo.getMarketId());
    //     Map paramMap = new HashMap();
    //
    //     //根据createInboundShipmentPlan接口获取返回的【shipmentid】和【DestinationFulfillmentCenterId】给下面接口使用
    //     List<String> shipmentIdList = new ArrayList<>();
    //     List<String> centerIdList = new ArrayList<>();
    //     Address shipFromAddress = new Address();
    //
    //     List<InboundShipmentItem> list = new ArrayList<>();
    //     for (int i = 0; i < jsonArray.size(); i++) {
    //         JSONObject jb = jsonArray.getJSONObject(i);
    //         String shipmentId = jb.getString("ShipmentId");
    //         String centerId = jb.getString("DestinationFulfillmentCenterId");
    //         //返回的object【address】
    //         shipFromAddress = jb.getObject("shipFromAddress", Address.class);
    //         shipmentIdList.add(shipmentId);
    //         centerIdList.add(centerId);
    //
    //         //创建入库运输计划传过来的数据 需要保存到本地数据库中
    //         AsinShipmentDo asinShipmentDo1 = jb.getObject("asinShipmentDo", AsinShipmentDo.class);
    //         asinShipmentDo1.setMSkus(Integer.valueOf(jb.getString("mskuNum")));
    //         asinShipmentDo1.setCreateTime(new Date());
    //         log.debug("执行插入AsinShipment表操作");
    //         dao.insert(asinShipmentDo1);
    //
    //         JSONArray ja = jb.getJSONArray("asinShipmentItemDoList");
    //         List<InboundShipmentPlanRequestItem> itemDoList = ja.toJavaList(InboundShipmentPlanRequestItem.class);
    //        for (int j = 0; j < itemDoList.size(); j++) {
    //            AsinShipmentItemDo asinShipmentItemDo = new AsinShipmentItemDo();
    //            asinShipmentItemDo.setShipmentId(shipmentId);
    //            asinShipmentItemDo.setCommoditySku(itemDoList.get(j).getSellerSKU());
    //            asinShipmentItemDo.setShippedQuantity(itemDoList.get(j).getQuantity());
    //            asinShipmentItemDo.setDeclareQuantity(itemDoList.get(j).getQuantity());
    //            log.debug("执行插入AsinShipmentItem表操作");
    //            asinShipmentItemDao.insert(asinShipmentItemDo);
    //         }
    //
    //         //获取返回数据中list【items】 这些是创建入库亚马逊接口需要的参数
    //         JSONArray jsArray = jb.getJSONArray("Items");
    //         for (int j = 0; j < jsArray.size(); j++) {
    //             JSONObject jsObject = jsArray.getJSONObject(j);
    //             InboundShipmentItem item = new InboundShipmentItem();
    //             item.setSellerSKU(jsObject.getString("SellerSKU"));
    //             item.setQuantityShipped(Integer.valueOf(jsObject.getString("Quantity")));
    //             item.setShipmentId(shipmentIdList.get(i));
    //             list.add(item);
    //         }
    //
    //         InboundShipmentHeader shipHeader = new InboundShipmentHeader();
    //         shipHeader.setShipmentName(shipmentName);
    //         shipHeader.setShipFromAddress(shipFromAddress);
    //         shipHeader.setDestinationFulfillmentCenterId(centerIdList.get(i));
    //         shipHeader.setShipmentStatus("WORKING");
    //         shipHeader.setLabelPrepPreference("SELLER_LABEL");
    //         shipHeader.setIntendedBoxContentsSource("NONE");
    //
    //         paramMap.put("InboundShipmentHeader", shipHeader);
    //         paramMap.put("InboundShipmentItems", list);
    //         paramMap.put("MarketplaceId", marketPlaceId);
    //
    //         AsinShipmentDo asinShipmentDo = new AsinShipmentDo();
    //         asinShipmentDo.setShipmentId(shipmentIdList.get(i));
    //         //根据shipmentid获取id 用于update
    //         AsinShipmentDo asinDo = dao.selectOne(new QueryWrapper<AsinShipmentDo>().eq("shipment_id", shipmentIdList.get(i)));
    //         asinShipmentDo.setId(asinDo.getId());
    //         asinShipmentDo.setShipmentName(shipmentName);
    //         dao.updateById(asinShipmentDo);
    //
    //         //返回的jsonArray可能有多条,循环调用接口和处理
    //         String body = null;
    //         try {
    //             body = AmazonUtil.spAPidoPOST(GlobalConstants.AmazonSPAPIURL + "/fba/inbound/v0/shipments/" + shipmentIdList.get(i), getAccessToken(shopId), getAwsSTSSessionToken(shopDo.getMarketId()), paramMap, JSONObject.toJSONString(paramMap));
    //         } catch (Exception e) {
    //             e.printStackTrace();
    //         }
    //         if (body != null) {
    //             JSONObject payload = JSONObject.parseObject(body).getJSONObject("payload");
    //             if (payload == null) {
    //                 JSONArray errors = JSONObject.parseObject(body).getJSONArray("errors");
    //                 JSONObject jsonObject = errors.getJSONObject(0);
    //                 log.debug(jsonObject.getString("message"));
    //                 throw new BizException(jsonObject.getString("message"));
    //             } else {
    //
    //             }
    //         }
    //     }
    // }
    //
    // @Override
    // public void updateInboundShipment(Long shopId, Long marketPlaceId, Long id, String shipmentName, List<InboundShipmentPlanRequestItem> itemList) {
    //     ShopDo shopDo = shopDao.selectById(shopId);
    //     if (shopDo == null) {
    //         throw new BizException("请选择店铺");
    //     }
    //     AmazonMarketPlaceDo amazonMarketPlaceDo = amazonMarketPlaceDao.selectById(marketPlaceId);
    //     //市场
    //     AmazonMarketDo amazonMarketDo = amazonMarketDao.selectById(amazonMarketPlaceDo.getMarketId());
    //     Map paramMap = new HashMap();
    //
    //     ShipAddress shipFromAddress = new Address();
    //     //从数据库中取到发货地址信息(信息在createShipment接口中保存到了本地)
    //     AsinShipmentDo asDo = dao.selectOne(new QueryWrapper<AsinShipmentDo>().eq("id", id));
    //     shipFromAddress.setName(asDo.getAddressName());
    //     shipFromAddress.setAddressLine1(asDo.getAddressLine());
    //     shipFromAddress.setDistrictOrCounty(asDo.getDistrictOrCounty());
    //     shipFromAddress.setCity(asDo.getCity());
    //     shipFromAddress.setStateOrProvinceCode(asDo.getStateOrProvinceCode());
    //     shipFromAddress.setCountryCode(asDo.getCountryCode());
    //     shipFromAddress.setPostalCode(asDo.getPostalCode());
    //     //拿到修改该条数据的shipmentId和destination
    //     String shipmentId = asDo.getShipmentId();
    //     String destination = asDo.getDestination();
    //
    //     List<InboundShipmentItem> list = new ArrayList<>();
    //     //拿到ShipmentItem表里的数据 调用亚马逊接口作参数
    //     List<AsinShipmentItemDo> itemDoList = asinShipmentItemDao.selectList(new QueryWrapper<AsinShipmentItemDo>().eq("shipment_id", shipmentId));
    //     if (itemDoList.size() == 0) {
    //         throw new BizException("对不起，找不到该货件编号下的货物信息！");
    //     }
    //     for (int j = 0; j < itemDoList.size(); j++) {
    //         InboundShipmentItem item = new InboundShipmentItem();
    //         item.setSellerSKU(itemDoList.get(j).getCommoditySku());
    //         item.setQuantityShipped(itemDoList.get(j).getShippedQuantity());
    //         item.setShipmentId(itemDoList.get(j).getShipmentId());
    //         list.add(item);
    //     }
    //     InboundShipmentHeader shipHeader = new InboundShipmentHeader();
    //     shipHeader.setShipmentName(shipmentName);
    //     shipHeader.setShipFromAddress(shipFromAddress);
    //     shipHeader.setDestinationFulfillmentCenterId(destination);
    //     shipHeader.setShipmentStatus("WORKING");
    //     shipHeader.setLabelPrepPreference("SELLER_LABEL");
    //     shipHeader.setIntendedBoxContentsSource("NONE");
    //
    //     paramMap.put("InboundShipmentHeader", shipHeader);
    //     paramMap.put("InboundShipmentItems", list);
    //     paramMap.put("MarketplaceId", marketPlaceId);
    //
    //     String body = null;
    //     try {
    //         body = AmazonUtil.spAPidoPUT(GlobalConstants.AmazonSPAPIURL + "/fba/inbound/v0/shipments/" + shipmentId, getAccessToken(shopId), getAwsSTSSessionToken(shopDo.getMarketId()), paramMap, JSONObject.toJSONString(paramMap));
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //     if (body != null) {
    //         JSONObject payload = JSONObject.parseObject(body).getJSONObject("payload");
    //         if (payload == null) {
    //             JSONArray errors = JSONObject.parseObject(body).getJSONArray("errors");
    //             JSONObject jsonObject = errors.getJSONObject(0);
    //             log.debug(jsonObject.getString("message"));
    //             throw new BizException(jsonObject.getString("message"));
    //         }
    //     }
    //
    //     AsinShipmentDo asinShipmentDo = new AsinShipmentDo();
    //     //根据shipmentid获取id 用于update
    //     AsinShipmentDo asinDo = dao.selectOne(new QueryWrapper<AsinShipmentDo>().eq("shipment_id", shipmentId));
    //     asinShipmentDo.setId(asinDo.getId());
    //     asinShipmentDo.setShipmentName(shipmentName);
    //     asinShipmentDo.setUpdateTime(new Date());
    //     dao.updateById(asinShipmentDo);
    //
    //     for (int k = 0; k < itemList.size(); k++) {
    //         AsinShipmentItemDo itemDo = new AsinShipmentItemDo();
    //         itemDo.setId(itemDoList.get(k).getId());
    //         itemDo.setShipmentId(shipmentId);
    //         //修改时申报数量数量只能和创建时数量相差5%
    //         float quantityCreate = itemDoList.get(k).getDeclareQuantity();
    //         float quantityLowest = (float) (quantityCreate * 0.95);
    //         float quantityHighest = (float) (quantityCreate * 1.05);
    //         if (itemList.get(k).getQuantity() >= quantityLowest & itemList.get(k).getQuantity() <= quantityHighest) {
    //             itemDo.setShippedQuantity(itemList.get(k).getQuantity());
    //         }else {
    //             int k1 = k + 1;
    //             throw new BizException("第"+k1+"条申报数量修改有误，修改申报数量与创建申报数量相差不能超过5%，请正确修改申报数量！" +
    //                     "创建申报数量为:【"+quantityCreate+"】，您修改的申报数量为：【"+itemList.get(k).getQuantity()+"】");
    //         }
    //         log.debug("执行修改item表shippedQuantity操作");
    //         asinShipmentItemDao.updateById(itemDo);
    //     }
    // }
    //
    // @Override
    // public Object updateInboundShipmentInit(Long id) {
    //     updateInboundShipmentRes res = asinShipmentDao.selectInitInfo(id);
    //     if (res.getShopId() == 1 && res.getMarketPlaceId() ==16) {
    //         res.setShopName("MWPO-日本");
    //     }
    //     if (res.getShopId() == 33 && res.getMarketPlaceId() ==17) {
    //         res.setShopName("EOWO-测试服");
    //     }
    //     if (res.getShopId() ==33 && res.getMarketPlaceId() ==16) {
    //         res.setShopName("EOWO-日本");
    //     }
    //     return res;
    // }
    //
    // @Override
    // public List addShipmentFile(MultipartFile file, Long userId, Long companyId) throws FileNotFoundException {
    //     if (file == null) {
    //         throw new BizException("请选择要上传的文件");
    //     }
    //     if (org.apache.commons.lang.StringUtils.isEmpty(file.getName())) {
    //         throw new BizException("文件名不能为空");
    //     }
    //     String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
    //     if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) &&
    //             !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
    //         throw new BizException("文件格式不正确");
    //     }
    //     List<ShipmentExcelImport> shipmentExcelImports = new ArrayList<>();
    //     try {
    //         shipmentExcelImports = ExcelUtils.importExcel(file, 1, 0, ShipmentExcelImport.class);
    //     } catch (IOException e) {
    //         e.printStackTrace();
    //         throw new BizException(e.getMessage());
    //     }
    //     if (shipmentExcelImports.size() > 200) {
    //         throw new BizException("导入的数据不要超过200条");
    //     }
    //     if (shipmentExcelImports.size() == 0) {
    //         throw new BizException("模板为空，请正确输入信息");
    //     }
    //
    //     List<ShipmentExcelImport> list = new ArrayList<>();
    //     for (ShipmentExcelImport excelImport : shipmentExcelImports) {
    //         if ("".equals(excelImport.getCommoditySku())) {
    //             throw new BizException("请完善商品SKU信息");
    //         }
    //         if ("".equals(excelImport.getTitle())) {
    //             throw new BizException("请完善标题信息");
    //         }
    //         if ("".equals(excelImport.getAsin())) {
    //             throw new BizException("请填入本地SKU信息");
    //         }
    //         if (excelImport.getQuantity() == null) {
    //             throw new BizException("请填入申报数量");
    //         }
    //         ShipmentExcelImport shipment = new ShipmentExcelImport();
    //         BeanUtils.copyProperties(excelImport, shipment);
    //         list.add(shipment);
    //     }
    //     return list;
    // }
}
